package com.example.booksystem.action;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(urlPatterns = "/code",loadOnStartup = 1)
public class VerCodeServlet extends HttpServlet {
    Random random = new Random();

    //获取随机数
    private String getRandomStr(){
        String str = "23456789ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(str.length());
            char ch = str.charAt(index);
            buffer.append(ch);
        }
        return buffer.toString();
    }

    //获取字体颜色
    private Color getBackColor(){
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);

        return new Color(red,green,blue);
    }

    //获取背景颜色
    private Color getForeColor(Color bg){
        int red = 255 - bg.getRed();
        int green = 255 - bg.getGreen();
        int blue = 255 - bg.getBlue();

        return new Color(red,green,blue);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应格式
        resp.setContentType("image/jpeg");
        //图片对象
        BufferedImage bufferedImage = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
        //画布
        Graphics graphics = bufferedImage.getGraphics();
        Color backColor = getBackColor();
        graphics.setColor(backColor);
        graphics.fillRect(0,0,80,30);
        //字体
        Color foreColor = getForeColor(backColor);
        graphics.setColor(foreColor);
        graphics.setFont(new Font("黑体",Font.BOLD,26));
        //随机数
        String randomStr = getRandomStr();
        HttpSession session = req.getSession();
        session.setAttribute("code",randomStr);
        graphics.drawString(randomStr,10,28);
        //噪点
        for (int i = 0; i < 30; i++) {
            graphics.setColor(Color.WHITE);
            int x = random.nextInt(80);
            int y = random.nextInt(30);
            graphics.fillRect(x,y,1,1);
        }
        //图片输入到响应流
        ServletOutputStream stream = resp.getOutputStream();
        ImageIO.write(bufferedImage,"jpeg",stream);


    }
}
